package graphics;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;

public class Zbuffer2 extends Image implements IZbuffer {
	private	Color	c[][] = null;
	private float	z[][] = null;
	private int		width, height;
	private Color	background;

	public Zbuffer2(int width, int height, Color bgColor) {
		this.background = bgColor;
		this.width = width;
		this.height = height;

		c	= new Color[width][height];
		z	= new float[width][height];
		clear();
	}

	public void setPixel(int x, int y, float z, Color c) {
		if	(	(x>=0)
			&&	(x<width)
			&&	(y>=0)
			&&	(y<height)
			&&	(z > this.z[x][y])
			)
		{
			this.c[x][y] = c;
		}
	}
	public Color getPixel(int x, int y) {
		if	(	(x>=0)
				&&	(x<width)
				&&	(y>=0)
				&&	(y<height)
				)
		{
			return this.c[x][y];
		} else {
			return this.background;
		}
	}

	@Override
	public int getWidth(ImageObserver observer) {
		return this.width;
	}

	@Override
	public int getHeight(ImageObserver observer) {
		return this.height;
	}

	@Override
	public ImageProducer getSource() {
		return null;
	}

	@Override
	public Graphics getGraphics() {
		return null;
	}

	@Override
	public Object getProperty(String name, ImageObserver observer) {
		return null;
	}

	@Override
	public int getWidth() {
		return this.width;
	}

	@Override
	public int getHeight() {
		return this.height;
	}

	@Override
	public void clear() {
		int x, y;
		for(x=0; x<width; x++) {
			for(y=0; y<height; y++) {
				c[x][y] = background;
				z[x][y] = Float.MIN_VALUE;
			}
		}
	}

	public BufferedImage getArea(Rectangle R) {
		// Create the new image needed
		int				width = R.width;
		int 			height = R.height;
		if (width>0 && height>0) {
			BufferedImage	img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB );
			paintImage(img, R.x, R.y);
			return img;
		} else {
			return null;
		}
	}

	public void	paintImage(BufferedImage img, int srcX, int srcY) {
		int width = img.getWidth();
		int height = img.getHeight();
		int	x = srcX;
		int y = srcY;

		Color	C;

		for ( int rc = 0; rc < height; rc++ ) {
			for ( int cc = 0; cc < width; cc++ ) {
				C = getPixel(cc+x, rc+y);
				img.setRGB(cc, rc, C.getRGB() );
			}
		}
	}


}
